//
//  SettingCell.m
//  AutoMate
//
//  Created by hao on 2018/3/1.
//  Copyright © 2018年 songlei. All rights reserved.
//

#import "SettingCell.h"

//重新设定view的Y、X、Width、Height值
#define SET_FRAME_Y(view, newY) view.frame = CGRectMake(view.frame.origin.x, newY, view.frame.size.width, view.frame.size.height)
#define SET_FRAME_X(view, newX) view.frame = CGRectMake(newX, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
#define SET_FRAME_H(view, newH) view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, newH)
#define SET_FRAME_W(view, newW) view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, newW, view.frame.size.height)

// icon和标题、 描述标题和右图片的间距
static CGFloat const CellIconTitleMargin = 10.0;

#define CELL_COLOR_RGBA(r, g, b, a)           [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define CELL_COLOR_RGB(r, g, b)               CELL_COLOR_RGBA(r, g, b, 1.0f)

@interface SettingCell () <UITextFieldDelegate>

/** 左边的图标 */
@property (nonatomic, weak) UIImageView *iconIV;

/** 标题 */
@property (nonatomic, weak) UILabel *titleL;

/** 标题详情 */
@property (nonatomic, weak) UILabel *detailL;

/** 右侧图标可能还有选中时的图标，使用Button */
@property (nonatomic, weak) UIButton *detailBtn;

/** 箭头 */
@property (nonatomic, weak) UIImageView *arrowImageView;

/** 右边编辑框 */
@property (nonatomic, weak) UITextField *textField;

/** 右侧开关 */
@property (nonatomic, weak) UISwitch *switchView;

///
@property (nonatomic, weak) UIView *customRightView;

@end

@implementation SettingCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
                        indexPath:(NSIndexPath *)indexPath
                        itemModel:(SettingItemModel *)itemModel
{
    // 重用标识
    static NSString *mineSettingIdentifier = @"mineSettingIdentifier";
    // 获得cell
    SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:mineSettingIdentifier];
    if (cell == nil) {
        cell = [[SettingCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:mineSettingIdentifier];
        if (itemModel.highlightColor) {
            cell.selectedBackgroundView = [[UIView alloc] init];
            cell.selectedBackgroundView.backgroundColor = itemModel.highlightColor;
        } else {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.indexPath = indexPath;
    cell.itemModel = itemModel;
    return cell;
}

- (instancetype)initWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath itemModel:(SettingItemModel *)itemModel
{
    return [SettingCell cellWithTableView:tableView indexPath:indexPath itemModel:itemModel];
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    // 存在自定义cell
    if (_itemModel.customCell) {
        [self.contentView addSubview:_itemModel.customCell];
        _itemModel.customCell.frame = self.contentView.bounds;
        return ;
    }
    CGFloat cellWidth = self.contentView.bounds.size.width;
    CGFloat cellHeight = self.contentView.bounds.size.height;
    CGFloat margin = _itemModel.cellDefaultMargin;
    // 设置标题
    CGSize titleSize;
    if (_itemModel.attrTitle) {
        self.titleL.attributedText = _itemModel.attrTitle;
        titleSize = _itemModel.attrTitle.size;
    } else {
        self.titleL.text = _itemModel.title;
        self.titleL.textColor = _itemModel.titleColor ? : [UIColor blackColor];
        titleSize = [_itemModel.title sizeWithAttributes:@{NSFontAttributeName: self.titleL.font}];
    }
    
    self.titleL.frame = CGRectMake(margin, (cellHeight-titleSize.height)*0.5, titleSize.width, titleSize.height);
    
    // 设置图标，标题左边
    if (_itemModel.icon) {
        self.iconIV.image = _itemModel.icon;
        CGFloat iconW = _itemModel.iconSize.width ? : _itemModel.icon.size.width;
        CGFloat iconH = _itemModel.iconSize.height ? : _itemModel.icon.size.height;
        CGFloat iconY = (cellHeight - iconH)*0.5;
        self.iconIV.frame = CGRectMake(margin, iconY, iconW, iconH);
        // 更新标题的位置
        SET_FRAME_X(self.titleL, CGRectGetMaxX(self.iconIV.frame) + CellIconTitleMargin);
    }
    
    // 右边view的MaxX
    CGFloat rightMaxX = cellWidth - _itemModel.cellDefaultMargin;
    if (!_itemModel.hiddenArrow) {
        rightMaxX -= (CellIconTitleMargin+self.arrowImageView.image.size.width);
    }
    // 标题和箭头图标之间的距离
    CGFloat laveMaxWidth = cellWidth - titleSize.width - _itemModel.cellDefaultMargin - CellIconTitleMargin;
    
    /// 不知道为什么直接设置 _itemModel.rightView.hidden = YES; 不起作用，需要从self.contentView取出设置才会隐藏
    self.customRightView.hidden = YES;
    switch (_itemModel.rightViewType) {
            case CellRightViewTypeNone:
        {
            
        }
            break;
            case CellRightViewTypeLabel:
        {
            // 描述标题
            CGSize detailSize;
            if (_itemModel.attrDetail) {
                self.detailL.attributedText = _itemModel.attrDetail;
                detailSize = _itemModel.attrDetail.size;
            } else {
                self.detailL.text = _itemModel.detailTitle;
                self.detailL.textColor = _itemModel.detailTitleColor ? : CELL_COLOR_RGB(200, 200, 200);
                detailSize = [_itemModel.detailTitle sizeWithAttributes:@{NSFontAttributeName: self.detailL.font}];
            }
            
            CGFloat detailX = CGRectGetMaxX(self.titleL.frame) + CellIconTitleMargin;
            CGFloat detailY = (cellHeight - detailSize.height)*0.5;
            CGFloat detailW = rightMaxX - detailX;
            // 显示箭头时，重新调整位置
            if (!_itemModel.hiddenArrow) {
                detailW -= (CGRectGetWidth(self.arrowImageView.frame));
            }
            self.detailL.frame = CGRectMake(detailX, detailY, detailW, detailSize.height);
            self.detailL.hidden = NO;
            _detailBtn.hidden = YES;
            _switchView.hidden = YES;
            _textField.hidden = YES;
            //            NSLog(@"self.detailL.frame = %@", NSStringFromCGRect(self.detailL.frame));
        }
            break;
            case CellRightViewTypeTextField:
        {
            CGSize size = _itemModel.rightViewSize;
            CGFloat width = size.width ? : (laveMaxWidth <= 120 ? laveMaxWidth : 120);
            CGFloat height = size.height ? : (cellHeight <= 44 ? cellHeight : 44);
            CGFloat x = rightMaxX - width;
            CGFloat y = (cellHeight - height)*0.5;
            // 创建一个输入框放置在描述的位置
            self.textField.frame = CGRectMake(x, y, width, height);
            self.textField.hidden = NO;
            _detailL.hidden = YES;
            _detailBtn.hidden = YES;
            _switchView.hidden = YES;
            _textField.hidden = YES;
        }
            break;
            case CellRightViewTypeSwitch:
        {
            CGFloat width = CGRectGetWidth(self.switchView.frame);
            CGFloat x = rightMaxX - width;
            CGFloat y = (cellHeight - CGRectGetHeight(self.switchView.frame))*0.5;
            self.switchView.frame = CGRectMake(x, y, 0, 0);
            if (_detailL) {
                SET_FRAME_W(_detailL, CGRectGetWidth(_detailL.frame) - width);
            }
            self.switchView.hidden = NO;
            _detailL.hidden = YES;
            _detailBtn.hidden = YES;
            _textField.hidden = YES;
        }
            break;
            //        case CellRightViewTypeArrow:
            //        {
            //            _detailL.hidden = YES;
            //            _detailBtn.hidden = YES;
            //            _switchView.hidden = YES;
            //            _textField.hidden = YES;
            //            if (!_itemModel.hiddenArrow) {
            //                self.arrowImageView.hidden = NO;
            //            }
            //        }
            break;
            case CellRightViewTypeImage:
        {
            [self.detailBtn setImage:_itemModel.detailImage forState:UIControlStateNormal];
            [self.detailBtn setImage:_itemModel.detailSelectImage forState:UIControlStateSelected];
            CGFloat width = _itemModel.detailImageSize.width ? : _itemModel.detailImage.size.width;
            CGFloat height = _itemModel.detailImageSize.height ? : _itemModel.detailImage.size.height;
            CGFloat x = rightMaxX - width;
            CGFloat y = (cellHeight - height)*0.5;
            // 显示箭头时，重新调整位置
            if (!_itemModel.hiddenArrow) {
                x -= (CGRectGetWidth(self.arrowImageView.frame));
            }
            self.detailBtn.frame = CGRectMake(x, y, width, height);
            self.detailBtn.hidden = NO;
            _detailL.hidden = YES;
            _switchView.hidden = YES;
            _textField.hidden = YES;
        }
            break;
            case CellRightViewTypeCustom:
        {
            if (_itemModel.rightView) {
                [self.customRightView addSubview:_itemModel.rightView];
                CGSize size = _itemModel.rightViewSize;
                // 校验确保rightView不超过可用区间
                CGFloat vWidth = size.width <= laveMaxWidth ? size.width : laveMaxWidth;
                CGFloat x = rightMaxX - vWidth;
                CGFloat y = (cellHeight-size.height)*0.5;
                //                _itemModel.rightView.frame = CGRectMake(x, y, vWidth, size.height);
                _detailL.hidden = YES;
                _detailBtn.hidden = YES;
                _switchView.hidden = YES;
                _textField.hidden = YES;
                self.customRightView.frame = CGRectMake(x, y, vWidth, size.height);
                _itemModel.rightView.frame = self.customRightView.bounds;
                self.customRightView.hidden = NO;
            }
        }
            break;
        default:
            break;
    }
    
    // 右边的箭头图标
    if (_itemModel.hiddenArrow) {
        self.arrowImageView.hidden = YES;
    } else {
        self.arrowImageView.hidden = NO;
    }
    
    if (_itemModel.highlightColor) {
        self.selectedBackgroundView.frame = self.contentView.bounds;
    }
    
    if (_itemModel.normalColor) {
        self.contentView.backgroundColor = _itemModel.normalColor;
    } else {
        self.contentView.backgroundColor = [UIColor whiteColor];
    }
}

//- (void)setItemModel:(SettingItemModel *)itemModel
//{
//    _itemModel = itemModel;
//}

- (UILabel *)titleL
{
    if (!_titleL) {
        UILabel *label = [[UILabel alloc] init];
        //        label.backgroundColor = RandomColor;
        [self.contentView addSubview:label];
        label.font = kAdaptedSystemFont(14);
        _titleL = label;
    }
    return _titleL;
}

- (UIImageView *)iconIV
{
    if (!_iconIV) {
        UIImageView *iv = [[UIImageView alloc] init];
        [self.contentView addSubview:iv];
        _iconIV = iv;
    }
    return _iconIV;
}

- (UILabel *)detailL
{
    if (!_detailL) {
        UILabel *label = [[UILabel alloc] init];
        //        label.backgroundColor = RandomColor;
        label.textAlignment = NSTextAlignmentRight;
        label.font = kAdaptedSystemFont(14);
        [self.contentView addSubview:label];
        _detailL = label;
    }
    return _detailL;
}

- (UIButton *)detailBtn
{
    if (!_detailBtn) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.contentView addSubview:btn];
        [btn addTarget:self action:@selector(detailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _detailBtn = btn;
    }
    return _detailBtn;
}

- (UITextField *)textField
{
    if (!_textField && _itemModel.rightViewType == CellRightViewTypeTextField) {
        UITextField *text = [[UITextField alloc] init];
        text.borderStyle = UITextBorderStyleNone;
        text.textAlignment = NSTextAlignmentRight;
        text.placeholder = @"请输入";
        text.delegate = self;
        text.backgroundColor = [UIColor lightGrayColor];
        [self.contentView addSubview:text];
        _textField = text;
    }
    return _textField;
}

- (UISwitch *)switchView
{
    if (!_switchView) {
        UISwitch *sv = [[UISwitch alloc] init];
        [sv addTarget:self action:@selector(swicthViewOnClick:) forControlEvents:UIControlEventValueChanged];
        [self.contentView addSubview:sv];
        _switchView = sv;
    }
    return _switchView;
}

- (UIImageView *)arrowImageView
{
    if (!_arrowImageView) {
        UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:CELL_ARROW_IMAGE_NAME]];
        [self.contentView addSubview:iv];
        _arrowImageView = iv;
    }
    CGSize imgSize = _arrowImageView.image.size;
    CGSize cellSize = self.contentView.frame.size;
    CGFloat x = cellSize.width - _itemModel.cellDefaultMargin - imgSize.width;
    CGFloat y = (cellSize.height - imgSize.height)*0.5;
    _arrowImageView.frame = CGRectMake(x, y, imgSize.width, imgSize.height);
    return _arrowImageView;
}

- (UIView *)customRightView
{
    if (!_customRightView) {
        UIView *_view = [[UIView alloc] init];
        _view.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_view];
        _customRightView = _view;
    }
    return _customRightView;
}

- (void)detailBtnClick:(UIButton *)btn
{
    if (_itemModel.detailSelectImage && !btn.isSelected) {
        btn.selected = YES;
    } else if (_itemModel.detailImage && btn.isSelected) {
        btn.selected = NO;
    }
    if (_itemModel.rightViewClickBlock) {
        _itemModel.rightViewClickBlock(self);
    }
}

- (void)swicthViewOnClick:(UISwitch *)switchView
{
    NSLog(@"%@", switchView.isOn ? @"YES" : @"NO");
    if (_itemModel.rightViewClickBlock) {
        _itemModel.rightViewClickBlock(self);
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_itemModel.rightViewClickBlock) {
        _itemModel.rightViewClickBlock(self);
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"%s", __func__);
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //    NSLog(@"%s", __func__);
    [textField resignFirstResponder];
    return YES;
}

//- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason
//{
//    NSLog(@"%s", __func__);
//}

//- (void)setHighlighted:(BOOL)highlighted
//{
//    [super setHighlighted:highlighted];
//    if (self.itemModel.highlightColor && highlighted) {
//        [UIView animateWithDuration:0.1 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{
//            self.backgroundColor = self.itemModel.highlightColor;
//        } completion:nil];
//    }
//}

@end


